import os

from tools import MuTool


class MuVideo:
    def __init__(self):
        self.tools = MuTool()
        self.message = None
        self.env = self.tools.get_os()
    def get_error_message(self):
        return self.message
    def __video_to_mp4(self, input_video_path:str, output_video_path:str):
        from moviepy import VideoFileClip
        try:
            video_clip = VideoFileClip(input_video_path)
            video_clip.write_videofile(output_video_path, codec='libx264', audio_codec='aac')
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def __video_to_gif(self, input_video_path:str, output_video_path:str):
        from moviepy import VideoFileClip
        try:
            fps = 10
            clip = VideoFileClip(input_video_path)
            clip.write_gif(output_video_path, fps=fps)
        except Exception as e:
            self.message = str(e)
            return False
        return True
    def video_to_other(self, input_video_path:str, output_video_path:str,file_type:str|None=None):
        if self.tools.is_empty(input_video_path):
            self.message = "输入文件路径不能为空"
            return False
        if not os.path.exists(input_video_path):
            self.message = "输入文件不存在"
            return False
        if not file_type and not output_video_path:
            self.message = "文件类型和输出文件路径不能同时为空"
            return False
        if not file_type and output_video_path:
            file_type = self.tools.get_file_suffix(output_video_path)
        if file_type not in ['gif','mp4']:
            self.message = "不支持的输出文件类型"
            return False
        if not os.path.exists(os.path.dirname(output_video_path)):
            os.makedirs(os.path.dirname(output_video_path), exist_ok=True)
        if file_type == 'gif':
            return self.__video_to_gif(input_video_path,output_video_path)
        elif file_type == 'mp4':
            return self.__video_to_mp4(input_video_path,output_video_path)
        self.message = "不支持的输出文件类型"
        return False